package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.commons.util.Constants;
import com.itheima.commons.util.JwtUtils;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //校验登录
    public Map login(Map map) {
        //获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //判断用户名密码是否为空
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new BusinessException("用户名或者密码为空");
        }
        //校验验证码是否正确
        String s = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(s)||!s.equals(verificationCode)){
            throw new BusinessException("验证码有误");
        }
        //根据用户名查询用户
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(lambdaQueryWrapper);
        String password1 = admin.getPassword();
        password = SecureUtil.md5(password);
        //判断用户名密码是否一致
        if (admin==null||!password.equals(password1)){
            throw new BusinessException("用户名或者密码");
        }
        //6、通过JWT生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        claims.put("id", admin.getId());
        String token = JwtUtils.getToken(claims);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("token",token);
        return map1;
    }

    public AdminVo profile() {
        //根绝用户ID查询当前用户
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Admin::getId, AdminHolder.getUserId());
        Admin admin = adminMapper.selectOne(queryWrapper);
        return AdminVo.init(admin);
    }
}
